package org.lsp.opencvauto.windowApi;


import com.sun.jna.platform.DesktopWindow;
import com.sun.jna.platform.WindowUtils;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

@Component
public class WindowDispose {


    private static final String SAVE_FILE = "wechat_messages.txt";
    private static final int HOTKEY_ID = 1;
    private static BufferedImage prevFrame = null;

    // 窗口标志常量
    private static final int SWP_SHOWWINDOW = 0x0040;
    private static final int SW_NORMAL = 1;
    private static volatile AtomicBoolean stopFlag = new AtomicBoolean(false);

    private static final Logger log = LoggerFactory.getLogger(WindowDispose.class);

    /*
    * 置顶窗口激活，并且显示在最上层
    * */
    public  Map<String,Object> windowTop() {
        Map<String,Object> map = new HashMap<>();
        // 获取微信窗口句柄
        AtomicReference<DesktopWindow> weix= new AtomicReference<>();
        List<DesktopWindow> allWindows = WindowUtils.getAllWindows(false);
        allWindows.stream().filter(win->win.getTitle().equals("微信")).forEach(win->{
            log.info("微信窗口是否可见: " + User32.INSTANCE.IsWindowVisible(win.getHWND()));
            WinUser.WINDOWPLACEMENT windowplacement=new WinUser.WINDOWPLACEMENT();
            User32.INSTANCE.GetWindowPlacement(win.getHWND(),windowplacement);
            log.info("微信窗口是否最小化: " + windowplacement.showCmd);
            if (User32.INSTANCE.IsWindowVisible(win.getHWND())) {
                User32.INSTANCE.SetForegroundWindow(win.getHWND());
                Map<String, Integer> center = center(win);
                map.put("x",center.get("x"));
                map.put("y",center.get("y"));
                map.put("width", center.get("width"));
                map.put("height", center.get("height"));
                weix.set(win);
            }
            if (windowplacement.showCmd==User32.SW_SHOWMINIMIZED){
                User32.INSTANCE.ShowWindow(win.getHWND(),User32.SW_RESTORE);
                Map<String, Integer> center = center(win);
                map.put("x",center.get("x"));
                map.put("y",center.get("y"));
                map.put("width", center.get("width"));
                map.put("height", center.get("height"));
                weix.set(win);
            }
        });
        map.put("DesktopWindow", weix.get());
        return map;
    }

    /*
    * 窗口居中显示
    * */
    private Map<String,Integer> center(DesktopWindow hWnd) {
        WinDef.RECT rect=new WinDef.RECT();
        User32.INSTANCE.GetWindowRect(hWnd.getHWND(),rect);
        log.info("微信窗口的坐标 left: {} right: {} top :{} bottom :{} ",rect.left,rect.right,rect.top,rect.bottom);
        int screenWidth = User32.INSTANCE.GetSystemMetrics(User32.SM_CXSCREEN);
        int screenHeight = User32.INSTANCE.GetSystemMetrics(User32.SM_CYSCREEN);
        log.info(" window屏幕宽高  screenWidth: {} screenHeight: {}" , screenWidth,screenHeight);
        int width =rect.right-rect.left;
        int height = rect.bottom-rect.top;
        log.info("窗口的宽: {} 高 ：{}",width,height);
        int x =  (screenWidth - width)/2;
        int y =  (screenHeight - height)/2;
        log.info("x: " + x + ", y: " + y);
        log.info("窗口：left  "+rect.left+" 窗口right："+rect.right+"窗口top："+rect.top+"窗口bottom："+rect.bottom);
        User32.INSTANCE.SetWindowPos(hWnd.getHWND(), null, x, y, width, height, SWP_SHOWWINDOW);
        System.out.println("微信窗口已调整为 " + width + "x" + height + " 并居中显示");
        Map<String,Integer> map = new HashMap<>();
        map.put("x", x);
        map.put("y", y);
        map.put("width", width);
        map.put("height", height);
        return map;
    }

    /*
     *窗口捕捉
     * */
    public BufferedImage captureRegion(Rectangle region) {
        try {
            Robot robot = new Robot();
            log.info("窗口截图保存");
            return robot.createScreenCapture(region);
        } catch (AWTException e) {
            log.info("窗口截图保存失败，原因",e.getMessage());
            throw new RuntimeException("屏幕捕获失败: " + e.getMessage(), e);
        }
    }

    /*
    * 监听window窗口，检测新消息
    * */
    public  boolean detectNewMessage(BufferedImage currentFrame) {
        if (prevFrame == null) {
            prevFrame = currentFrame;
            return false;
        }
        // 转换为灰度图像
        BufferedImage prevGray = convertToGrayscale(prevFrame);
        BufferedImage currentGray = convertToGrayscale(currentFrame);

        int width = currentGray.getWidth();
        int height = currentGray.getHeight();
        int diffCount = 0;

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int prevPixel = prevGray.getRGB(x, y) & 0xFF;
                int currentPixel = currentGray.getRGB(x, y) & 0xFF;
                if (Math.abs(prevPixel - currentPixel) > 30) {
                    diffCount++;
                }
            }
        }

        prevFrame = currentFrame;
        return diffCount > 1000; // 可调整阈值
    }

    /**
     * 将图像转换为灰度图jia
     * */
    private static BufferedImage convertToGrayscale(BufferedImage image) {
        BufferedImage grayImage = new BufferedImage(
                image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return grayImage;
    }





}
